package Stock;

import java.util.ArrayList;
import java.util.List;

public  class ATR {
	private  static final  byte MOVING_AVERAGE = 14;
	private static List<Float> m_ATR;

	public static  List<Float> getATRFromTransactions(List<Transaction> transactions){
		computeATR(transactions);	
		return m_ATR;
	}
		 
	private static void computeATR(List<Transaction> transactions){
		TR tr = new TR(transactions);
		m_ATR = new ArrayList<>();

		CalculateATR(tr.getTR());
	}
	
	private  static void CalculateATR(List<Float> listTR) {
		 
		float average=0;
		float calculated=0;
	 
		for(int i = 0;i<listTR.size();i++){
			if(i<14){
				average += listTR.get(i);
				m_ATR.add(calculated);
			}else{
			 if(i==14)
				m_ATR.add(average/MOVING_AVERAGE);
			 
			 else{
				 //(ATR vorige * 13 + TR current)/14;
				calculated=m_ATR.get(m_ATR.size()-1)*(MOVING_AVERAGE-1)+ listTR.get(i);
				m_ATR.add(calculated/MOVING_AVERAGE);
			 }
			}
		}
		
		System.out.println(" TR size: " + listTR.size() + " ATR - " + m_ATR.size());
 
	}

	 static class TR {

		private List<Transaction> m_Transtactions;
		private List<Float> m_TR;
		 

		public TR(List<Transaction> transactions) {
			m_Transtactions = transactions;
			m_TR = new ArrayList<>();
			computeTR();
		}

		public List<Float> getTR(){
			return m_TR;
		}
		
		private void computeTR() {
			//to prevent an if in the for statement so that it goes faster
			m_TR.add(calculateTR(m_Transtactions.get(0), m_Transtactions.get(0)));
			for (int i = 1; i < m_Transtactions.size(); i++) {
				m_TR.add(calculateTR(m_Transtactions.get(i - 1),
						m_Transtactions.get(i)));
			}
		}

		private float calculateTR(Transaction previous, Transaction current) {
			float currentRange = calculateCurrentRange(current);
			float highClose = calculateHighClose(previous, current);
			float lowClose = calculateLowClose(previous, current);

			return Math.max(currentRange, Math.max(highClose, lowClose));
		}

		private float calculateCurrentRange(Transaction current) {
			return current.getHigh() - current.getLow();
		}
		private float calculateHighClose(Transaction previous, Transaction current) {
			return Math.abs((current.getHigh() - previous.getClose()));
		}
		private float calculateLowClose(Transaction previous, Transaction current) {
			return Math.abs((current.getLow() - previous.getClose()));
		}
	}
	
}


